﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Reflection;

namespace MossDAL.DotNet.ServiceHelpers
{
    public class DotNetServiceHelper<T> : BaseServiceHelper<T> where T : SharepointListItem, new()
    {
        public IList<T> FetchListItems(string query) 
        {
            IList<T> items = new List<T>();
            if(String.IsNullOrEmpty(SharepointListName))
            {
                MemberInfo info = typeof(T);

                object[] atts = info.GetCustomAttributes(typeof(SharepointListNameAttribute), true);
                if (atts.Count() > 0)
                {
                    SharepointListNameAttribute att = (SharepointListNameAttribute)atts[0];
                    SharepointListName = att.ListName;
                }
            }

            XmlDocument doc = new XmlDocument();
            string s = "<q>"+ query + "</q>";
            doc.LoadXml(s);

            XmlNode q = doc.FirstChild.ChildNodes[0];
            XmlNode viewfields = doc.FirstChild.ChildNodes[1];
            XmlNode options = doc.FirstChild.ChildNodes[2];
            ListsService.Lists lc = new ListsService.Lists();
            lc.Url = ServiceEndpointAddress;
            if (Credentials != null)
                lc.Credentials = Credentials;
            else
                lc.UseDefaultCredentials = true;
            
            XmlNode results = lc.GetListItems(SharepointListName, null, q, viewfields, PageSize.ToString(), options, null);
            XElement elm = XElement.Parse(results.OuterXml);
            foreach (XElement element in elm.Elements().ToList()[0].Elements())
            {
                T item = new T();
                item.Load(element);
                items.Add(item);
            }

            return items;
        }
    }
}
